﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace RemoteCode
{
    //Thanks to DragonHunter!
    internal class SyncHelper
    {
        private object SyncListLock = new object();
        private SortedList<int, SyncObject> SyncObjects = new SortedList<int, SyncObject>();
        private object syncPulse = new object();
        private bool abort = false;

        public void DisableAllWaits()
        {
            //this is preventing deadlocks on disconnect, we don't like deadlocks do we :3
            abort = true;
        }
        public void ReEnable()
        {
            abort = false;
        }

        public int CreateSyncObject()
        {
            lock (SyncListLock)
            {
                int id = GenerateSyncId();
                SyncObjects.Add(id, new SyncObject(id));
                return id;
            }
        }
        public object WaitForSyncId(int id, int timeout = 0)
        {
            if (!SyncObjects.ContainsKey(id))
                throw new Exception("Out of sync");

            lock (SyncObjects[id])
            {
                int time = 0;
                while (true)
                {
                    if (SyncObjects[id].Wait(100)) break;

                    time += 100;
                    if (abort)
                        throw new Exception("Aborted");
                    if (timeout != 0 && time > timeout)
                        throw new Exception("Timed out");
                }
                object ret = SyncObjects[id].ReturnObject;

                SyncObjects.Remove(id);

                return ret;
            }
        }
        public void PulseSyncId(int id, object ret)
        {
            lock (syncPulse)
            {
                if (SyncObjects.ContainsKey(id))
                    SyncObjects[id].Pulse(ret);
            }
        }
        public void Clear()
        {
            DisableAllWaits();
            SyncObjects.Clear();
        }

        private int GenerateSyncId()
        {
            Random r = new Random(DateTime.Now.Millisecond);
            int id = r.Next(int.MinValue, int.MaxValue);
            while (id == 0 || SyncObjects.ContainsKey(id))
                id = r.Next(int.MinValue, int.MaxValue);
            return id;
        }
    }
}
